package com.ifish.leetcode.problem.algorithm;

import com.ifish.leetcode.problem.BaseLeetCodeProblem;

/**
 * Created by iFish on 17/7/11.
 */

// Write a function to find the longest common prefix string amongst an array of strings.

public class _0014 extends BaseLeetCodeProblem {
    @Override
    public String title() {
        return "Longest Common Prefix";
    }

    @Override
    public void run() {
        super.run();

        String strs[] = new String[]{"1", "1", "12"};
        String prefix = longestCommonPrefix(strs);
        printResult(prefix);
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";

        StringBuffer sb = new StringBuffer();
        int len = strs[0].length();
        for (int i = 0; i < len; i++) {
            char c = strs[0].charAt(i);
            boolean end = false;
            for (int j = 1; j < strs.length; j++) {
                if (strs[j].length() <= i || strs[j].charAt(i) != c) {
                    end = true;
                    break;
                }
            }
            if (end) {
                break;
            }
            sb.append(c);
        }
        return sb.toString();
    }
}
